import { Injectable } from '@angular/core';
import { AngularFireAuth } from '@angular/fire/auth';
import { AngularFireDatabase } from '@angular/fire/database';
import { AngularFirestore } from '@angular/fire/firestore';
import * as firebase from 'firebase/app';
import { switchMap, map } from 'rxjs/operators';
import { Observable } from 'rxjs';

export interface User {
  uid: string;
  email: string
}
export interface Message {
  createdAt: firebase.default.firestore.FieldValue;
  id: string;
  from: string;
  msg: string;
  fromName: string;
  myMsg: boolean;
}

@Injectable({
  providedIn: 'root'
})
export class ChatService {
  currentUser: User = null
  constructor(
    private afAuth: AngularFireAuth,
    private afs: AngularFirestore,
    private afdb: AngularFireDatabase
  ) {
    this.afAuth.onAuthStateChanged(user => {
      console.log('changed', user)
      this.currentUser = user
    })
  }
  // 注册
  async signUp({ email, password }) {
    const credential = await this.afAuth.createUserWithEmailAndPassword(email, password)
    console.log('credential', credential)
    const uid = credential.user.uid
    return this.afs.doc(`users/${uid}`).set({
      uid,
      email: credential.user.email
    })
  }
  // 登录
  signIn({ email, password }) {
    return this.afAuth.signInWithEmailAndPassword(email, password)
  }
  // 登出
  signOut() {
    return this.afAuth.signOut()
  }

  // 发送消息
  addChatMessage(msg) {
    return this.afs.collection('messages').add({
      msg: msg, // 发送消息
      from: this.currentUser.uid, // 发送人uid
      createdAt: firebase.default.firestore.FieldValue.serverTimestamp() // 发送时间，以服务器为准
    });
  }
  // 获取用户对应的消息
  getChatMessages() {
    let users = [];
    // 获取用户 再去获取用户对应的消息
    return this.getUsers().pipe(
      switchMap(res => {
        users = res;
        return this.afs.collection('messages', ref => ref.orderBy('createdAt')).valueChanges({ idField: 'id' }) as Observable<Message[]>;
      }),
      // 消息处理
      map(messages => {
        // Get the real name for each user
        for (let m of messages) {
          m.fromName = this.getUserForMsg(m.from, users);
          // 如果当前uid等于form 自己发送的消息
          m.myMsg = this.currentUser.uid === m.from;
        }
        return messages
      })
    )
  }
  // 获取用户
  private getUsers() {
    return this.afs.collection('users').valueChanges({ idField: 'uid' }) as Observable<User[]>;
  }
  // 获取用户消息
  private getUserForMsg(msgFromId, users: User[]): string {
    for (let usr of users) {
      if (usr.uid == msgFromId) {
        return usr.email;
      }
    }
    return 'Deleted';
  }

}
